package com.heima.wemedia.filter;


import com.heima.wemedia.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;


/**
 * @author AWei
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    List<String> urlList = Arrays.asList(
            "/login/in",
            "/v2/api-docs"
    );

    /**
     * @param exchange 封装了 请求 和 响应对象
     * @param chain    链对象
     * @return 过滤结果
     * @Description 过滤方法
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //查询路径是否需要拦截，如果不需要拦截，直接放行
        String reqUrl = request.getURI().getPath();
        for (String url : urlList) {
            if (reqUrl.contains(url)) {
                // 放行
                return chain.filter(exchange);
            }
        }
        //2. 获取请求头中的token信息
        String token = request.getHeaders().getFirst("token");
        //2.1 为空，则直接终止请求  并响应未认证状态
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3. 验证token是否有效
        try {
            // 解析token，获取载荷信息
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i < 1) {
                //3.1 有效，则获取token中存储的用户id，将用户ID存储到请求头中，然后放行请求
                Integer id = claims.get("id", Integer.class);
                // 改变请求的状态
                ServerHttpRequest newRequest = request.mutate().header("userId", String.valueOf(id)).build();
                // 改变exchange状态，并放行请求  向下一个过滤器传递
                return chain.filter(exchange.mutate().request(newRequest).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("jwt token 解析出现异常==>{}", e);
        }
        //3.2 无效，则直接终止请求，并响应未认证状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}